import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../utils/logger.dart';

class WebPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  const WebPage(this.arguments, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  late String url;
  late final controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setBackgroundColor(const Color(0x00000000))
    ..setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int p) {
          progress.value = p;
        },
        onPageStarted: (String url) {
          logger.info('page start: $url');
        },
        onPageFinished: _onPageFinished,
        onWebResourceError: (WebResourceError error) {},
        onNavigationRequest: (NavigationRequest request) {
          return NavigationDecision.navigate;
        },
      ),
    );

  final progress = ValueNotifier<int>(0);

  String title = '...';

  @override
  void initState() {
    super.initState();
    url = widget.arguments['url'];
    controller.loadRequest(Uri.parse(url));
  }

  void _onPageFinished(String url) async {
    String? pageTitle = await controller.getTitle();
    logger.info('page finished: $url');
    if (pageTitle == null) {
      return;
    }
    logger.info('title: $pageTitle');
    setState(() {
      title = pageTitle;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        actions: [
          IconButton(
            onPressed: () {
              launchUrl(Uri.parse(url));
            },
            icon: const Icon(Icons.input),
          ),
        ],
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(0),
          child: SizedBox(
            height: 0,
            child: ValueListenableBuilder<int>(
              valueListenable: progress,
              builder: (context, value, child) {
                if (value > 0 && value < 100) {
                  return OverflowBox(
                    maxHeight: 2,
                    child: LinearProgressIndicator(
                      value: value.toDouble(),
                    ),
                  );
                }
                return const SizedBox.shrink();
              },
            ),
          ),
        ),
      ),
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.white,
      body: SafeArea(
        child: WebViewWidget(
          controller: controller,
        ),
      ),
      bottomNavigationBar: null,
    );
  }
}
